﻿using System.Data.Common;
using System;
using System.Data;

namespace MyFrameWork.Dam
{
    public class DBManager : IDisposable
    {
        private DbTransaction _DbTransaction = null;

        public DbTransaction Transaction { get { return _DbTransaction; } }

        private DbConnection _DbConnection = null;

        public DbConnection Connection { get { return _DbConnection; } }

        public DBManager()
        { 
        
        }

        public DBManager(DbConnection connection) 
        {
            _DbConnection = connection;
        }

        public void BeginTransaction() 
        {
            _DbConnection.Open();
            _DbTransaction = _DbConnection.BeginTransaction();
        }

        public void BeginTransaction(IsolationLevel isolationLevel)
        {
            _DbConnection.Open();
            _DbTransaction = _DbConnection.BeginTransaction(isolationLevel);
        }

        public void Commit()
        {
            _DbTransaction.Commit();
            _DbConnection.Close();
        }

        public void Rollback()
        {
            _DbTransaction.Rollback();
            _DbConnection.Close();
        }

        public bool IsTtansaction()
        {
            return (_DbTransaction != null && _DbTransaction.Connection != null);
        }

        public void Dispose()
        {
            if (_DbTransaction != null && _DbTransaction.Connection != null)
            {
                _DbTransaction.Rollback();
            }

            if (_DbTransaction != null)
            {
                _DbTransaction.Dispose();
            }

            _DbTransaction = null;

            if (_DbConnection != null && _DbConnection.State == ConnectionState.Open)
            {
                _DbConnection.Close();
            }

            if (_DbConnection != null)
            {
                _DbConnection.Dispose();
            }

            _DbConnection = null;
        }
    }
}